package day2.service;

import day2.beans.User;
import day2.util.Utils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public int insertUser(User u)throws Exception{
        String sql = "insert into t_user (myname,age,address) values(?,?,?)";
        PreparedStatement st = Utils.getSt(sql);
        st.setObject(1,u.getName());
        st.setObject(2,u.getAge());
        st.setObject(3,u.getAddress());
        return st.executeUpdate();
    }

    public int updateUserNameById(Integer id,String name)throws Exception{
        String sql = "update t_user set name=? where id=?";
        PreparedStatement st = Utils.getSt(sql);
        st.setObject(1,name);
        st.setObject(2,id);
        return st.executeUpdate();
    }

    public int deleteById(Integer id)throws Exception{
        String sql = "delete from t_user where id=?";
        PreparedStatement st = Utils.getSt(sql);
        st.setObject(1,id);
        return st.executeUpdate();
    }

    public List<User>selectUserByName(String name)throws Exception{
        String sql = "select * from t_user where myname=?";
        PreparedStatement st = Utils.getSt(sql);
        st.setObject(1,name);
        ResultSet rs = st.executeQuery();
        List<User> list = new ArrayList();
        while (rs.next()){
            list.add(new User(rs.getInt("id"),rs.getString("myname"),rs.getInt("age"),rs.getString("address")));
        }
        return list;
    }
    public List<User>selectUserLikeName(String name)throws Exception{
        String sql = "select * from t_user where myname like ?";
        PreparedStatement st = Utils.getSt(sql);
        st.setObject(1,name);
        ResultSet rs = st.executeQuery();
        List<User> list = new ArrayList();
        while (rs.next()){
            list.add(new User(rs.getInt("id"),rs.getString("myname"),rs.getInt("age"),rs.getString("address")));
        }
        return list;
    }
}
